﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    
    public class AppletUserQueryController : ApiController
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] AppletUser AU)
        {
            ReturnObject RO = new ReturnObject();
            if (string.IsNullOrEmpty(AU.AUUserAccount) && string.IsNullOrEmpty(AU.AUEmail))
            {
                Logger.Warn("查询参数无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "查询参数无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                try
                {
                    await connection.OpenAsync();
                    var query = @"SELECT AUID, AUUsername, AUUserAccount, AUUserPassword, AUPhoneNumber, AUWeChatID, AUEmail, AUCreationDate 
                                  FROM AppletUser
                                  WHERE (AUUserAccount = @UserAccount OR @UserAccount IS NULL)
                                    AND (AUEmail = @Email OR @Email IS NULL)";

                    SqlParameter[] parameters = {
                        new SqlParameter("@UserAccount", SqlDbType.NVarChar, 50) { Value = (object)AU.AUUserAccount ?? DBNull.Value },
                        new SqlParameter("@Email", SqlDbType.NVarChar, 50) { Value = (object)AU.AUEmail ?? DBNull.Value }
                    };

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var users = new List<AppletUser>();
                            while (await reader.ReadAsync())
                            {
                                users.Add(new AppletUser
                                {
                                    AUID = reader.GetInt32(0),
                                    AUUsername = reader.GetString(1),
                                    AUUserAccount = reader.GetString(2),
                                    AUUserPassword = reader.GetString(3),
                                    AUPhoneNumber = reader.GetString(4),
                                    AUWeChatID = reader.GetString(5),
                                    AUEmail = reader.GetString(6),
                                    AUCreationDate = reader.GetDateTime(7)
                                });
                            }
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = users;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warn("查询失败: " + ex.Message);
                    RO.Status = HttpStatusCode.InternalServerError;
                    RO.Message = "Error";
                    RO.Data = null;
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "查询失败: " + ex.Message);
                }
            }
        }
    }
}